package cn.yzgy.yzgyoa.common.utils;

import cn.yzgy.yzgyoa.common.entity.ReportRecord;
import cn.yzgy.yzgyoa.common.crsp.StatusCode;
import cn.yzgy.yzgyoa.common.exception.SystemException;
import cn.yzgy.yzgyoa.common.report.ExcelGen;
import cn.yzgy.yzgyoa.common.report.ReportGenResult;
import cn.yzgy.yzgyoa.ucenter.entity.UserInfoDetail;
import org.springframework.stereotype.Component;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 导出Excel工具类
 * 提取可复用代码
 *
 * @author Yqsen
 * @since 2020-9-30 08:31:13
 */
@Component
public class ExportUtil {

    private static final int BUF_SIZE = 1024;

    /**
     * 写文件
     * @param reportRecord 报表记录表
     * @throws IOException IO读写异常
     */
    public static void outPutFile(ReportRecord reportRecord, HttpServletResponse response) throws IOException
    {
        File file = new File(reportRecord.getFullPath());
        if (file.exists()) {
            response.setContentType(MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(reportRecord.getFullPath()));
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(reportRecord.getFileName(), "UTF-8"));
            OutputStream os = response.getOutputStream();
            byte[] buf = new byte[BUF_SIZE];
            BufferedInputStream is = new BufferedInputStream(new FileInputStream(file));
            while (is.read(buf) != -1) {
                os.write(buf, 0, buf.length);
                os.flush();
            }
        }
    }

    /**
     * 获取组装查询条件 表头所用
     * @param queryDto 查询对象
     * @return 查询条件
     */
    public static StringBuilder getQueryCondition(Object queryDto){
        // 组装查询条件
        StringBuilder stringBuilder = new StringBuilder("查询参数：");
        Field[] fields = queryDto.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object cur = null;
            try {
                cur = field.get(queryDto);
            } catch (IllegalAccessException ignore) {}
            if (cur != null) {
                stringBuilder.append(String.format(" | 参数：%s 值：%s", field.getName(), cur.toString()));
            }
        }
        return stringBuilder;
    }

    public static String createAndInsert(ExcelGen excelGen, UserInfoDetail curUser){

        ReportGenResult genRes = excelGen.createReport();
        if (!genRes.getSuccess()) {
            throw new SystemException(StatusCode.IO_EXCEPTION, "生成报表失败，请稍后再试");
        }

        //流水号  订单号
        long snowflakeId = SnowflakeIdWorker.getNext();
        String string = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //插入报表记录表
        new ReportRecord().setCreateBy(curUser.getUid())
                .setFileName(genRes.getFileName())
                .setFullPath(genRes.getFullPath())
                .setDownloadId(string+snowflakeId)
                .setFilePath(genRes.getFilePath())
                .insert();
        return string+snowflakeId;
    }
}
